package com.example.ndk_demo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    private String TAG ="MainActivity";
    private File mCascadeFile;
    private void copyCascadeFile(){
        try {
            InputStream is = getResources().openRawResource(R.raw.haarcascade_frontalface_alt2);
            File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
            mCascadeFile = new File(cascadeDir,"lbpcascade_frontalface2.xml");
            if (mCascadeFile.exists())return;
            FileOutputStream os = new FileOutputStream(mCascadeFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) !=-1){
                os.write(buffer,0,bytesRead);
            }
            is.close();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);

        tv.setText(stringFromJNI());
        ImageView imageView = findViewById(R.id.sample_img);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.c);
        imageView.setImageBitmap(bitmap);

        copyCascadeFile();
        loadFaceDetector(mCascadeFile.getAbsolutePath());

        findViewById(R.id.buttor).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: 开始灰度处理");
                Bitmap a = facedetector(bitmap);
                Log.d(TAG, "onClick: 开始灰度处理结果！");
                imageView.setImageBitmap(a);
            }
        });
    }
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
    //btmp 转灰度图
    public native Bitmap bmp2gray(Bitmap bitmap);
    //加载模型到c环境
    public  native void loadFaceDetector(String filePath);
    //检测人脸并画框
    public  native Bitmap facedetector(Bitmap bitmap);

}